﻿using ArchivingDataModel;
using ArchivingDataWebForms.Helpers;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace ArchivingDataWebForms.Pages.Organization
{
    public partial class WebFormOrganization : WebFormBase
    {
        private ArchivingDataEntities ent = new ArchivingDataEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.getRootOrganizations();
            }
        }

        protected void radcomboboxclass_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            this.getRootOrganizations();
        }

        private void getRootOrganizations()
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    byte orgclass = Convert.ToByte(this.radcomboboxclass.SelectedValue);
                    var rootOrgs = ent.Organizations.Include("TypeOfOrganization").Where(i => i.Is_External == orgclass && i.Organization_Parent_ID == null).Select(i => new { i.Organization_ID, i.Organization_Name_AR, i.Organization_Number, i.Organization_Parent_ID, Type_of_Organization_ID = i.TypeOfOrganization.Type_Of_Organization_ID, Type_Of_Organization_NameAR = i.TypeOfOrganization.Type_Of_Organization_NameAR }).ToArray();
                    this.RadTreeListOrgs.DataSource = rootOrgs;
                }
            }
            catch (Exception er)
            {
                //this.ShowNotification("حدث الخطا التالي اثناء الحفظ " + er.Message, NotificationIconType.Error);
            }
        }

        protected void RadTreeListOrgs_NeedDataSource(object sender, TreeListNeedDataSourceEventArgs e)
        {
            this.getRootOrganizations();
        }

        protected void RadTreeListOrgs_ChildItemsDataBind(object sender, TreeListChildItemsDataBindEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    long parentID = Convert.ToInt64(e.ParentDataKeyValues["Organization_ID"]);
                    byte orgclass = Convert.ToByte(this.radcomboboxclass.SelectedValue);
                    var childOrgs = ent.Organizations.Include("TypeOfOrganization").Where(i => i.Is_External == orgclass && i.Organization_Parent_ID == parentID).Select(i => new { i.Organization_ID, i.Organization_Name_AR, i.Organization_Number, i.Organization_Parent_ID,Type_of_Organization_ID=i.TypeOfOrganization.Type_Of_Organization_ID ,Type_Of_Organization_NameAR = i.TypeOfOrganization.Type_Of_Organization_NameAR }).ToArray();
                    e.ChildItemsDataSource = childOrgs;
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء النقل " + er.Message, NotificationIconType.Error);
            }
        }

        protected void RadTreeListOrgs_ItemDataBound(object sender, TreeListItemDataBoundEventArgs e)
        {
            try
            {
                if (e.Item is TreeListEditableItem)
                {
                    TreeListDataItem editedItem = e.Item as TreeListDataItem;
                    RadComboBox RadComboBoxOrgtype = (RadComboBox)e.Item.FindControl("RadComboBoxOrgtype");
                    if (RadComboBoxOrgtype != null)
                    {
                        var orgstypes = ent.TypeOfOrganizations.ToArray();
                        RadComboBoxOrgtype.DataSource = orgstypes;
                        RadComboBoxOrgtype.DataTextField = "Type_Of_Organization_NameAR";
                        RadComboBoxOrgtype.DataValueField = "Type_Of_Organization_ID";
                        RadComboBoxOrgtype.DataBind();
                        if (!(e.Item is TreeListDataInsertItem))
                        {
                            if (editedItem["Type_of_Organization_ID"] != null)
                            {
                                RadComboBoxOrgtype.SelectedValue = editedItem["Type_of_Organization_ID"].Text;
                            }
                        }
                        else if (orgstypes.Count() > 0)
                        {
                            this.radcomboboxclass.SelectedIndex = 0;
                        }
                    }
                    // e.Item.
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحفظ " + er.Message, NotificationIconType.Error);
                return;
            }
        }

        protected void RadTreeListOrgs_InsertCommand(object sender, TreeListCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    TreeListEditableItem editedItem = e.Item as TreeListEditableItem;
                    Hashtable newValues = new Hashtable();
                    e.Item.OwnerTreeList.ExtractValuesFromItem(newValues,editedItem,true);
                    string code = newValues["Organization_Number"].ToString();
                    string nameAr = newValues["Organization_Name_AR"].ToString();
                    RadComboBox RadComboBoxOrgtype = (RadComboBox)e.Item.FindControl("RadComboBoxOrgtype");
                    long orgTypeId = Convert.ToInt64(RadComboBoxOrgtype.SelectedValue);
                    byte orgclass = Convert.ToByte(this.radcomboboxclass.SelectedValue);
                    long? parentID = null;
                    if (newValues["Organization_Parent_ID"] != null && newValues["Organization_Parent_ID"].ToString() != "")
                    {
                        parentID = Convert.ToInt64(newValues["Organization_Parent_ID"]);
                    }

                    string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + nameAr);
                    ent.AddToOrganizations(new ArchivingDataModel.Organization
                    {
                        Organization_Number = code,
                        Organization_Name_AR = nameAr,
                        Organization_Name_EN = nameAr,
                        Is_External=orgclass,
                        TypeOfOrganization = ent.TypeOfOrganizations.FirstOrDefault(i=>i.Type_Of_Organization_ID==orgTypeId),
                        Organization_Parent_ID=parentID,
                        Organizations_Search = uniquetext
                    });
                    ent.SaveChanges();
                    this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحفظ " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }

        protected void RadTreeListOrgs_UpdateCommand(object sender, TreeListCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    TreeListEditableItem editedItem = e.Item as TreeListEditableItem;
                    Hashtable newValues = new Hashtable();
                    e.Item.OwnerTreeList.ExtractValuesFromItem(newValues, editedItem, true);
                    long id = Convert.ToInt64(newValues["Organization_ID"]);
                    string code = newValues["Organization_Number"].ToString();
                    string nameAr = newValues["Organization_Name_AR"].ToString();
                    RadComboBox RadComboBoxOrgtype = (RadComboBox)e.Item.FindControl("RadComboBoxOrgtype");
                    long orgTypeId = Convert.ToInt64(RadComboBoxOrgtype.SelectedValue);
                    byte orgclass = Convert.ToByte(this.radcomboboxclass.SelectedValue);
                    long? parentID = null;
                    if (newValues["Organization_Parent_ID"] != null && newValues["Organization_Parent_ID"].ToString() != "")
                    {
                        parentID = Convert.ToInt64(newValues["Organization_Parent_ID"]);
                    }

                    string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + nameAr);
                    var item = ent.Organizations.FirstOrDefault(i => i.Organization_ID == id);
                    item.Organization_Number = code;
                    item.Organization_Name_AR = nameAr;
                    item.Organization_Name_EN = nameAr;
                    item.TypeOfOrganization = ent.TypeOfOrganizations.FirstOrDefault(i => i.Type_Of_Organization_ID == orgTypeId);
                    item.Organizations_Search = uniquetext;
                    ent.SaveChanges();
                    this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحفظ " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }

        protected void RadTreeListOrgs_DeleteCommand(object sender, TreeListCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    long id = Convert.ToInt64((e.Item as TreeListDataItem).GetDataKeyValue("Organization_ID"));
                    if (!ent.Organizations.Any(i => i.Organization_Parent_ID == id))
                    {
                        ent.DeleteObject(ent.Organizations.FirstOrDefault(i => i.Organization_ID == id));
                        ent.SaveChanges();
                        this.ShowNotification("تم الحذف بنجاح", NotificationIconType.Ok);
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحذف " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
    }
}